﻿namespace UDKDevKitVSXCore.Classes
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.IO.Pipes;

    public class IpcCommandSender
    {
        private NamedPipeClientStream pipeClient;
        private StreamWriter streamWriter;
        private string channelName;

        public IpcCommandSender(string channelName)
        {
            if (String.IsNullOrEmpty(channelName))
            {
                Debug.Fail("ArgumentException - channelName");
                throw new ArgumentException("channelName");
            }

            this.channelName = channelName;
        }

        protected NamedPipeClientStream PipeClient
        {
            get
            {
                if (this.pipeClient == null)
                {
                    this.pipeClient = new NamedPipeClientStream(".", this.channelName, PipeDirection.Out);

                    // Connect to the pipe or wait until the pipe is available.
                    Debug.Write("Attempting to connect to pipe...");

                    pipeClient.Connect();

                    this.Dbg("Connected to pipe.");
                    this.Dbg(String.Format("There are currently {0} pipe server instances open.", pipeClient.NumberOfServerInstances));
                }

                return this.pipeClient;
            }
        }

        protected StreamWriter StreamWriter
        {
            get
            {
                if (this.streamWriter == null)
                {
                    this.streamWriter = new StreamWriter(this.PipeClient);
                    this.streamWriter.AutoFlush = true;
                }

                return this.streamWriter;
            }
        }

        public void Close()
        {
            this.pipeClient.Close();
        }

        protected void Send(string command)
        {
            if (String.IsNullOrEmpty(command))
            {
                Debug.Fail("ArgumentException - command");
                throw new ArgumentException("command");
            }

            if (command.Length < 1000)
            {
                this.Dbg(String.Concat("send ", command));
            }
            else
            {
                this.Dbg(String.Concat("send ", command.Substring(0, 1000)));
            }

            try
            {
                this.StreamWriter.WriteLine(command);
            }
            catch (Exception e)
            {
                Dbg(e.Message);
            }
        }

        private void Dbg(string msg)
        {
            Debug.WriteLine(msg, String.Concat("PipeClient - ", this.channelName));
        }
    }
}
